//
//  FingerDataBase.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/4/19.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "FingerDataBase.h"
#import "FMDatabase.h"

@implementation FingerDataBase
{
    FMDatabase *dataBase;
}


static FingerDataBase *instance = nil;

+(FingerDataBase *)getInstance
{
    @synchronized(self)
    {
        if (instance==nil)
        {
            instance = [[FingerDataBase alloc]init];
        }
    }
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        NSArray * arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * path = [arr objectAtIndex:0];
        // xxx.db 数据库的名字
        path = [path stringByAppendingPathComponent:@"FingerInfo.db"];
       // DLOG(@"path is %@...",path);
        // 根据绝对路径创建一个数据库
        dataBase = [FMDatabase databaseWithPath:path];
        // 打开数据库
        if (![dataBase open]) {
           // DLOG(@"can not open dataBase!");
        }
        [dataBase executeUpdate:@"CREATE TABLE if not exists finger_info (user_name text PRIMARY KEY,login_pwd text,finger_state text)"];
        
    }
    return self;
}

/**
 *  插入指定用户的指纹解锁的信息
 */
- (void)insertOrUpdateFingerInfoWithUserName:(NSString *)userName loginPwd:(NSString *)loginpwd fingerState:(NSString *)fingerState {
    NSString *sql = [NSString stringWithFormat:@"select * from finger_info Where user_name='%@'",userName];
    FMResultSet *rs1 = [dataBase executeQuery:sql];
    if([rs1 next]) {
        [dataBase executeUpdate:@"UPDATE finger_info SET login_pwd=?, finger_state=? WHERE user_name=?",loginpwd,fingerState,userName];
    }else {
        [dataBase executeUpdate:@"INSERT INTO finger_info (user_name,login_pwd,finger_state) VALUES (?,?,?)",userName,loginpwd,fingerState];
    }
    [rs1 close];
}

/**
 *  获取指定用户的指纹解锁信息
 */
- (NSString *)getFingerState:(NSString *)userName {
    
    NSString *sql = [NSString stringWithFormat:@"select finger_state from finger_info Where user_name='%@'",userName];
    FMResultSet *rs1=[dataBase executeQuery:sql];
    
    NSString *fingerState=@"-1";
    if([rs1 next]) {
        fingerState=[rs1 stringForColumnIndex:0];
    }
    [rs1 close];
    return fingerState;
}

/**
 *  更新指定用户的指纹解锁信息
 *
 *  @param userName     用户名
 *  @param fingerState  指纹解锁状态
 */
- (void)updateFingerState:(NSString *)userName fingerState:(NSString *)fingerState {
    [dataBase executeUpdate:@"UPDATE finger_info SET finger_state=? WHERE user_name=?",fingerState,userName];
}

/**
 *  删除指定用户的指纹解锁信息
 */
- (void)deleteFingerInfoWithUser:(NSString *)account {
    
    NSString *mysql=[NSString stringWithFormat:@"delete from finger_info Where user_name='%@'",account];
    [dataBase executeUpdate:mysql];
}

/**
 *  删除所有用户指纹解锁信息
 */
- (void)deleteAllFingerInfo {
    
    NSString *mysql=@"delete from finger_info";
    [dataBase executeUpdate:mysql];
}



@end
